import { defineStore, createPinia } from "pinia";
import { UserState } from "@/store/interface";
import { Login } from "@/api/interface";
import {
  login,
  logout,
  getInfo
} from '@/api/login'
import {
  getToken,
  setToken,
  removeToken,
  getPostId,
  setPostId,
  removePostId
} from '@/utils/auth'


export const UserStore = defineStore({
	// id: 必须的，在所有 Store 中唯一
	id: "UserStore",
	// state: 返回对象的函数
  state: (): UserState => ({
    token: getToken(),
    name: '',
    avatar: '',
    posts:[],
    roles: [],
    postUser:undefined,
    username:"",//账号
  }),
  getters: {},
  actions: {
    // 登录
    Login(userInfo: Login.ReqLoginForm) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const key = userInfo.key
      return new Promise((resolve: any, reject) :void => {
        login({username, password, code, key}).then(res => {
          setToken(res.data.token)
          if(res.data.currentPostId) {
            setPostId(res.data.currentPostId)
          }
          this.token = res.data.token
          this.name = res.data.postList[0]?.name
          this.posts = res.data.postList
          this.postUser = res.data.postList[0]
          resolve(res.data)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo() {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          this.posts = res.data.postList
          this.roles = res.data.roleList
          this.name = res.data.user.name
          this.username = res.data.user.acnt
          this.postUser = res.data.postList[0]
          resolve(res.data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    LogOut() {
      return new Promise((resolve: any, reject) => {
        logout().then(() => {
          removeToken()
          removePostId()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
  }
  //   // 职位改变
  //   ChangePostUser({commit,state}) {
  //     return new Promise((resolve,reject) =>{
  //       console.log(state)
  //       resolve()
  //     })
  //   },
  //   // 退出系统


  //   // 前端 登出
  //   FedLogOut({
  //     commit
  //   }) {
  //     return new Promise(resolve => {
  //       commit('SET_TOKEN', '')
  //       commit('SET_POSTS', []);
  //       removeToken()
  //       removePostId()
  //       resolve()
  //     })
  //   }
  // }
});

